package cn.plushine.controller;

import cn.plushine.pojo.Brand;
import cn.plushine.pojo.Goods;
import cn.plushine.pojo.POrder;
import cn.plushine.pojo.POrderItem;
import cn.plushine.service.BasePOrderService;
import cn.plushine.utils.ResMapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * 采购订单
 */
@Api(tags = "采购订单")
@Controller
@RestController
@RequestMapping("/admin/product/pOrder")
public class BasePOrderController {

    @Autowired
    BasePOrderService basePOrderService;

    // 获取采购订单
    @ApiOperation(value = "获取采购订单")
    @GetMapping("/get")
    public HashMap<String, Object> get() {
        try {
            // 获取采购订单
            List<POrder> pOrdersDB = basePOrderService.get();

            // 货物种类（size），货物总数（sum），购货总价（total），状态判断（flag）
            HashSet<Integer> hashSet = new HashSet<Integer>();
            int sum, flag;
            BigDecimal total;
            for (POrder pOrder : pOrdersDB) {
                hashSet.clear();
                sum = 0;
                flag = 0;
                total = BigDecimal.ZERO;
                for (POrderItem order : pOrder.getPOrders()) {
                    hashSet.add(order.getGoodsId());
                    sum += order.getNum();
                    flag += order.getFlag();
                    total = total.add(order.getInPrice().multiply(BigDecimal.valueOf(order.getNum())));
                }
                pOrder.setSize(hashSet.size());
                pOrder.setSum(sum);
                pOrder.setTotal(total);
                // 订单状态判断
                pOrder.setFlag(flag == 0 ? 0 : (flag == sum ? 2 : 1));
            }
            // 成功响应
            return ResMapUtils.encapsulation(200, "获取采购订单成功！", pOrdersDB);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "获取采购订单失败！", e.getMessage());
        }
    }

    // 获取货物列表
    @ApiOperation(value = "获取货物列表")
    @GetMapping("/getGoods")
    public HashMap<String, Object> getGoods() {
        try {
            // 获取货物列表
            List<Goods> goodsDB = basePOrderService.getGoods();
            // 成功响应
            return ResMapUtils.encapsulation(200, "获取货物列表成功！", goodsDB);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "获取货物列表失败！", e.getMessage());
        }
    }

    // 生成采购订单id
    @ApiOperation(value = "生成采购订单id")
    @GetMapping("/getId")
    public HashMap<String, Object> getId() {
        try {
            // 生成采购订单id
            String id = "CGDD" + System.currentTimeMillis();
            // 成功响应
            return ResMapUtils.encapsulation(200, "生成采购订单id成功！", id);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "生成采购订单id失败！", e.getMessage());
        }
    }


    // 查询货物单位（价格、供应商）
    @ApiOperation(value = "查询货物单位（默认价格和供应商）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "货物id", required = true, paramType = "path", dataType = "int", example = "1")
    })
    @GetMapping("/getUnit/{id}")
    public HashMap<String, Object> getUnit(@PathVariable int id) {
        try {
            // 查询货物单位（默认价格和供应商）
            Goods unitDB = basePOrderService.getUnit(id);
            // 成功响应
            return ResMapUtils.encapsulation(200, "查询货物单位（默认价格和供应商）成功！", unitDB);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "查询货物单位（默认价格和供应商）失败！", e.getMessage());
        }
    }

    // 添加采购订单
    @ApiOperation(value = "添加采购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "采购订单编号", required = true, paramType = "path", dataType = "String"),
            @ApiImplicitParam(name = "date", value = "创建日期", required = true, paramType = "path", dataType = "Date"),
            @ApiImplicitParam(name = "salesperson", value = "创建人", required = true, paramType = "path", dataType = "int", example = "1"),
            @ApiImplicitParam(name = "pOrderItems", value = "订单内容", required = true, paramType = "body", dataType = "List<POrderItem>")
    })
    @PostMapping("/add/{id}/{date}/{salesperson}")
    public HashMap<String, Object> add(@PathVariable String id, @PathVariable Date date, @PathVariable int salesperson, @RequestBody List<POrderItem> pOrderItems) {
        try {
            // 构造入库id
            String[] split = id.split("CGDD");
            String inputId = "RK" + split[1];

            // 添加采购订单
            basePOrderService.addPOrder(id, date, salesperson, inputId);
            /**
             * 给货物编号（先生成时间戳，再遍历添加，编号递增）
             */
            for (POrderItem pOrderItem : pOrderItems) {
                long timeMillis = System.currentTimeMillis();
                ArrayList<HashMap> ids = new ArrayList<>();
                for (int i = 0; i < pOrderItem.getNum(); i++) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("id", "HW" + (timeMillis++));
                    ids.add(i, hashMap);
                }
                // 添加采购订单记录
                basePOrderService.addPOrderItem(pOrderItem, ids, id);
            }
            // 成功响应
            return ResMapUtils.encapsulation(200, "添加采购订单成功！", null);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "添加采购订单失败！", e.getMessage());
        }
    }

    // 取消采购订单
    @ApiOperation(value = "取消采购订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "采购订单编号", required = true, paramType = "path", dataType = "String")
    })
    @DeleteMapping("/cancel/{id}")
    public HashMap<String, Object> cancel(@PathVariable String id) {
        try {
            // 取消采购订单
            basePOrderService.cancel(id);
            // 成功响应
            return ResMapUtils.encapsulation(200, "取消采购订单成功！", null);
        } catch (Exception e) {
            // 失败响应
            return ResMapUtils.encapsulation(201, "取消采购订单失败！", e.getMessage());
        }
    }
}
